import React, { useCallback, useEffect } from 'react';
import DataEdit from '../base/DataEdit';
import DataTable from '../base/DataTable';
import DataImport, { downLoadTemplateFile } from '../base/DataImport';
import IconFont from '../base/IconFont';
import { useReducer, useMemo, useRef } from 'react';
import {
  isManager,
  removeKeys,
  batchSubmit,
  getFolwRunInfo,
  abort,
  activation,
} from '@/services/workflow';
import { submitDatas } from '@/services/commCRUD';
import PageHeader from './PageHeader';
import { useModel } from 'umi';
import { format } from '@/utils/datetime';
import { renderNumber } from '@/utils/common';
import {
  Menu,
  Button,
  message,
  Space,
  Modal,
  Progress,
  Dropdown,
  Steps,
  Badge,
  List,
  Card,
  Row,
  Col,
  Alert,
  Descriptions,
  Divider,
} from 'antd';
import ProForm, { ProFormTextArea } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import _ from 'lodash';
import { DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

// 属性类型
type PropField = {
  /** 搜索要认定账户的后台dao名称*/
  searchDaoName: string;
  /** 搜索要认定账户表格column列表*/
  searchColumns: API.Column[];
  /** 搜索要认定账户control列表*/
  searchControls: API.Control[];
  /** 搜索要认定账户数据的主键名称*/
  searchKeyColName: string;
  /** 搜索要认定账户数据显示顺序*/
  searchOrder?: API.OrderItem;
  /** 任务列表的后台dao名称*/
  taskDaoName: string;
  /** 任务列表的表格column列表*/
  taskColumns: API.Column[];
  /** 导入配置名称，按照这个名称生成后台的配置表，必须唯一 */
  importName: string;
  /** 导入使用的控件列表 */
  importControls?: API.Control[];
  /** 导入模版的名称 */
  importTemplateName?: string;
  /** 最大的员工数量，用于生成员工占比录入编辑框 */
  maxEmplCount: number;
  /** 认定流程的标题 */
  title?: string;
  /** 认定流程的副标题，显示说明 */
  subhead?: string;
  /** 显示方式，申请，审批 */
  showType: 'apply' | 'approval';
  /** 是否变更 */
  isUpdate: boolean;
  /** 认定方式，占比，金额 */
  diviType?: 'percent' | 'money';
  /** 是否当前用户作为第一个认定员工 */
  userIsFirstEmpl: boolean;
  /** 流程进度窗口显示标题，标题由指定字段名称的值拼接而成 */
  titleColNames: string[];
  /** 是否按客户认定 */
  isClientDivi?: boolean;
  /** 是否可以设置变更日期 */
  canSetDiviDate?: boolean;
};
type StateField = {
  diviControls?: API.Control[];
  taskColumns?: API.Column[];
  importControls?: API.Control[];
  showImport?: boolean;
  showSeach?: boolean;
  isMg?: boolean;
  loading?: boolean;
  taskKeys?: number[];
  runStep?: JSX.Element;
  taskRows?: Record<string, any>[];
  searchKeys?: number[];
  searchSeeks?: API.WhereCause[];
  taskDaoName?: string;
  range?: string;
  cuid?: number;
};
const WorkflowDivi: React.FC<PropField> = (props) => {
  const [state, dispatch] = useReducer(
    (prevState: StateField, newState: StateField) => {
      return { ...prevState, ...newState };
    },
    {
      diviControls: [],
      taskColumns: [],
      importControls: [],
      showImport: false,
      showSeach: false,
      isMg: false,
      loading: false,
      taskKeys: [],
      runStep: undefined,
      taskRows: [],
      searchKeys: [],
      searchSeeks: [],
      taskDaoName: undefined,
      range: undefined,
      cuid: undefined,
    },
  );
  const tableRef = useRef<API.TableAction>();
  const formRef = useRef<ProFormInstance<any>>();
  const descFormRef = useRef<ProFormInstance<any>>();
  const { permTypes, curPermID, loadFlowDoing } = useModel('sysInfo', (ret) => ({
    permTypes: ret.getCurPermTypes(),
    curPermID: ret.curPermID,
    loadFlowDoing: ret.loadFlowDoing,
  }));
  const { user } = useModel('@@initialState', (ret) => ({
    user: ret.initialState?.user,
  }));
  const renderStep = (progress: number, status: string) => {
    const percent = Math.round(progress);
    return (
      <Progress
        percent={percent}
        size="small"
        status={
          status === '' ? 'normal' : (status as 'success' | 'normal' | 'exception' | 'active')
        }
      />
    );
  };
  useEffect(() => {
    isManager(curPermID)
      .then(function (data) {
        dispatch({ isMg: data });
      })
      .catch(function (ex) {
        console.error('判断流程管理员出错', ex);
      });
  }, [curPermID]);
  const initsearchSeeks = useCallback(() => {
    const seeks: API.WhereCause[] = [
      {
        WhereItems: [{ FieldName: props.searchKeyColName, Operator: '=', FieldValues: '0' }],
        RelationSign: 'AND',
      },
    ];
    return seeks;
  }, [props.searchKeyColName]);
  useEffect(() => {
    const diviConts: API.Control[] = [];
    const impConts: API.Control[] = props.importControls ? [...props.importControls!] : [];
    const extraCols: API.Column[] = [];
    const stepCol: API.Column = {
      title: '当前进度',
      key: 'StepName',
      render: (row: Record<string, any>) => renderStep(row.progress, row.status),
      width: 140,
      dispaly: true,
    };
    extraCols.push(stepCol);
    if (props.isUpdate) {
      extraCols.push({
        title: '变更次数',
        key: 'BGCS',
        dataIndex: 'BGCS',
        render: (bgcs) => <div style={{ color: 'red' }}>{bgcs}</div>,
        width: 120,
        dispaly: true,
      });
    }
    const tastCols: API.Column[] = [...extraCols, ...props.taskColumns];
    for (let i = 0; i < props.maxEmplCount; i++) {
      const dc1: API.Control = {
        name: `EMNO${i + 1}`,
        type: 'search',
        label: `员工${i + 1}`,
        dataType: 'string',
        grid: 12 / 24,
        placeholder: '请输入工号或名称...',
        fetch: {
          tableName: 'User',
          searchColumns: ['No', 'Name'],
          optionTpl: 'Name',
          valueTpl: 'No',
          isDao: true,
        },
        width: 200,
        rules: [],
      };
      const dc2: API.Control = {
        name: `DSVL${i + 1}`,
        type: 'number',
        dataType: 'number',
        label: props.diviType === 'money' ? `金额${i + 1}(元)` : `占比${i + 1}(%)`,
        grid: 12 / 24,
        rules:
          props.diviType === 'money'
            ? []
            : [{ min: 1, max: 100, message: `占比${i + 1}必须在1-100之间` }],
      };
      if (i === 0) {
        if (props.userIsFirstEmpl) {
          dc1.disabled = true;
          dc1.type = 'text';
          dc1.fetch = undefined;
        }
      }
      diviConts.push(dc1);
      diviConts.push(dc2);
      if (!_.isEmpty(impConts)) {
        const idc1: API.Control = {
          name: `EMNO${i + 1}`,
          type: 'text',
          label: `员工工号${i + 1}`,
          grid: 12 / 24,
          rules: i === 0 ? [{ required: true, message: `必须搜索和选择员工${i + 1}` }] : [],
        };
        impConts.push(idc1);
        impConts.push(dc2);
      }
      tastCols.push({
        title: `员工号${i + 1}`,
        dataIndex: `EMNO${i + 1}`,
        key: `EMNO${i + 1}`,
        width: 120,
        sorter: true,
        dispaly: true,
        filter: true,
        dataType: 'string',
      });
      tastCols.push({
        title: `员工名称${i + 1}`,
        key: `emnm${i + 1}`,
        dataIndex: `emnm${i + 1}`,
        width: 110,
        dispaly: true,
      });
      tastCols.push({
        title: props.diviType === 'money' ? `金额${i + 1}(元)` : `占比${i + 1}(%)`,
        dataIndex: `DSVL${i + 1}`,
        key: `DSVL${i + 1}`,
        width: 120,
        sorter: true,
        dispaly: true,
        dataType: 'number',
      });
    }
    if (props.canSetDiviDate && props.isUpdate && props.diviType === 'percent') {
      diviConts.push({
        name: 'DSDT',
        type: 'date',
        label: `变更日期`,
        grid: 12 / 24,
        rules: [{ required: true, message: '变更日期不能为空' }],
      });
    }
    const range = props.showType === 'apply' ? 'firstdoing' : 'doing';
    dispatch({
      diviControls: diviConts,
      importControls: impConts,
      taskColumns: tastCols,
      searchSeeks: initsearchSeeks(),
      taskDaoName: props.taskDaoName,
      range: range,
    });
  }, [
    props.importControls,
    props.maxEmplCount,
    props.userIsFirstEmpl,
    props.taskColumns,
    props.isUpdate,
    props.searchKeyColName,
    props.showType,
    initsearchSeeks,
    props.taskDaoName,
    props.diviType,
    props.canSetDiviDate,
  ]);
  const getTitle = useCallback(
    (row: Record<string, any>) => {
      const titles: JSX.Element[] = [];
      props.titleColNames.forEach((t, i) => {
        titles.push(<span key={i as React.Key}>{row[t]}</span>);
      });
      return <Space key={row.FRID}>{titles}</Space>;
    },
    [props.titleColNames],
  );
  const loadRunStep = useCallback(
    (runID: number) => {
      getFolwRunInfo(state.taskDaoName!, runID)
        .then(function (flowRunInfo) {
          const steps = flowRunInfo.stepList.map((s) => {
            let desc = '未开始';
            if (flowRunInfo.state === '2' && flowRunInfo.currStep === s.id) {
              desc = '已中止';
            } else if (s.state === '1') {
              desc = '办理中...';
            } else if (s.state === '2') {
              desc = '已办理';
            }
            const content: JSX.Element[] = [];
            s.executors.map((e) => {
              let color = '';
              if (e.desc === '待办...' || e.desc === '未办') {
                color = 'gray';
              } else if (e.desc.substring(0, 2) === '中止' || e.desc === '管理员强制提交') {
                color = '#FA541C';
              } else {
                color = '#0D993A';
              }
              const c = (
                <div key={e.id}>
                  <span>{`${e.name}(${e.department}):`}</span> <br />
                  <span style={{ color: color }}>{e.desc}</span>
                </div>
              );
              content.push(c);
            });
            const descTag = <div style={{ maxHeight: '200px', overflow: 'auto' }}>{content}</div>;
            return (
              <Steps.Step key={s.id} title={s.name + `【` + desc + `】`} description={descTag} />
            );
          });
          let status: 'wait' | 'process' | 'finish' | 'error' = 'process';
          if (flowRunInfo.state === '1') {
            status = 'finish';
          } else if (flowRunInfo.state === '2') {
            status = 'error';
          } else {
            const step = flowRunInfo.stepList[flowRunInfo.currStep - 1];
            if (step.appointer && step.appointer.length > 0 && step.executors.length == 0) {
              status = 'wait';
            }
          }
          const current = flowRunInfo.currStep - 1;
          const row = state.taskRows!.find((r) => r.FRID === runID);
          const runStep = (
            <Modal
              title={row ? getTitle(row) : ''}
              width={600}
              visible={true}
              onCancel={() => dispatch({ runStep: undefined })}
              footer={false}
            >
              <Steps direction="vertical" current={current} status={status}>
                {steps}
              </Steps>
            </Modal>
          );
          dispatch({ runStep: runStep });
        })
        .catch(function (ex) {
          console.error('判断流程管理员出错', ex);
          return;
        });
    },
    [getTitle, state.taskDaoName, state.taskRows],
  );
  const toolBar = useMemo(() => {
    if (_.isEmpty(permTypes)) {
      return;
    }
    const canImport = permTypes.indexOf('K') !== -1;
    const rangeChange = (key: string) => {
      let dao = props.taskDaoName;
      if (key === 'firstclosed' || key === 'closed') {
        dao = dao + 'His';
      }
      dispatch({ taskDaoName: dao, range: key, taskKeys: [] });
    };
    const deleteHandler = () => {
      if (_.isEmpty(state.taskKeys)) {
        message.info('请选择要删除的申请');
        return;
      }
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: `您确定要删除选中${state.taskKeys!.length}笔申请吗？`,
        onOk: () => {
          dispatch({ loading: true });
          removeKeys(props.taskDaoName, state.taskKeys!)
            .then(function (data) {
              if (data === 'OK') {
                if (!_.isEmpty(tableRef.current)) {
                  tableRef.current?.reload();
                }
                loadFlowDoing();
              }
            })
            .catch(function (ex) {
              console.error('删除流程出错', ex);
            })
            .finally(function () {
              dispatch({ loading: false });
            });
        },
        okText: '确认',
        cancelText: '取消',
      });
    };
    const batchSubmitHandler = () => {
      if (_.isEmpty(state.taskKeys)) {
        message.info('请选择要提交的申请');
        return;
      }
      const isMg = state.range !== 'doing' && state.isMg;
      Modal.confirm({
        title: (
          <div key="1">
            你确认要{isMg ? '强制' : ''}提交选中的
            <Badge
              count={state.taskKeys!.length}
              overflowCount={100}
              style={{ backgroundColor: '#87d068' }}
            />
            笔申请吗？{isMg ? '强制提交将跳过没有审批的节点直接生效！' : ''}
          </div>
        ),
        icon: <ExclamationCircleOutlined />,
        width: 800,
        content: (
          <div style={{ maxHeight: 600, overflow: 'auto' }}>
            <List
              size="small"
              dataSource={state.taskRows!.map((row) => (
                <>
                  {getTitle(row)}
                  {
                    <a
                      style={{ marginLeft: 10 }}
                      onClick={() => {
                        loadRunStep(row.FRID);
                      }}
                    >
                      进度
                    </a>
                  }
                </>
              ))}
              renderItem={(item) => <List.Item>{item}</List.Item>}
            />
            {isMg ? (
              <>
                <Divider />
                <ProForm formRef={descFormRef} layout="vertical" submitter={false}>
                  <ProFormTextArea
                    name="desc"
                    label="请填写强制提交的原因(200字以内)"
                    fieldProps={{ maxLength: 200 }}
                  />
                </ProForm>
              </>
            ) : null}
          </div>
        ),
        onOk: () => {
          let desc = '';
          if (isMg) {
            desc = descFormRef.current?.getFieldValue('desc');
            if (_.isEmpty(desc)) {
              message.error('您必须填写强制提交的原因');
              return;
            }
          }
          batchSubmit(props.taskDaoName, state.taskKeys!, user!.userID!, desc, '')
            .then(function () {
              message.success('流程提交成功');
              if (!_.isEmpty(tableRef.current)) {
                tableRef.current?.reload();
              }
              loadFlowDoing();
            })
            .catch(function (ex) {
              console.error('流程提交出错', ex);
            });
        },
        okText: '确认',
        cancelText: '取消',
      });
    };
    const abortHandler = () => {
      if (_.isEmpty(state.taskKeys)) {
        message.info('请选择要中止的申请');
        return;
      }
      Modal.confirm({
        title: '提示',
        content: `你确认要中止选中的${state.taskKeys!.length}笔申请吗？`,
        okText: '中止',
        cancelText: '取消',
        onOk: () => {
          abort(state.taskKeys!, props.taskDaoName)
            .then(function () {
              message.success('流程中止成功');
              if (!_.isEmpty(tableRef.current)) {
                tableRef.current?.reload();
              }
              loadFlowDoing();
            })
            .catch(function (ex) {
              console.error('流程中止出错', ex);
            });
        },
      });
    };
    const actHandler = () => {
      if (_.isEmpty(state.taskKeys)) {
        message.info('请选择要中止的申请');
        return;
      }
      Modal.confirm({
        title: '提示',
        content: `你确认要激活选中的${state.taskKeys!.length}笔申请吗？`,
        okText: '激活',
        cancelText: '取消',
        onOk: () => {
          activation(state.taskKeys!)
            .then(function () {
              message.success('流程激活成功');
              if (!_.isEmpty(tableRef.current)) {
                tableRef.current?.reload();
              }
              loadFlowDoing();
            })
            .catch(function (ex) {
              console.error('流程激活出错', ex);
            });
        },
      });
    };
    const isap = props.showType === 'apply';
    const menu = (
      <Menu onClick={(e) => rangeChange(e.key)}>
        <Menu.Item key={isap ? 'firstdoing' : 'doing'}>待办理</Menu.Item>
        <Menu.Item key={isap ? 'firstdone' : 'done'}>已提交</Menu.Item>
        <Menu.Item key={isap ? 'firstclosed' : 'closed'}>已完结</Menu.Item>
        <Menu.Item key={isap ? 'firstaborted' : 'aborted'}>已中止</Menu.Item>
        {state.isMg ? <Menu.Item key="manager">管理</Menu.Item> : null}
      </Menu>
    );
    return (
      <Space style={{ marginTop: -10, marginBottom: 10 }}>
        <Dropdown overlay={menu} trigger={['click']}>
          <Button type="ghost">
            {state.range === 'firstdoing' || state.range === 'doing'
              ? '待办理'
              : state.range === 'firstdone' || state.range === 'done'
              ? '已提交'
              : state.range === 'firstclosed' || state.range === 'closed'
              ? '已完结'
              : state.range === 'firstaborted' || state.range === 'aborted'
              ? '已中止'
              : '管理'}
            <DownOutlined />
          </Button>
        </Dropdown>
        {state.range === 'firstdoing' || state.range === 'doing' ? (
          <Button onClick={() => dispatch({ showSeach: true })}>
            <IconFont type="icon-xinzeng" />
            新增
          </Button>
        ) : null}
        {state.range === 'firstdoing' ? (
          <Button onClick={deleteHandler} disabled={state.loading}>
            <IconFont type="icon-shanchu" />
            删除
          </Button>
        ) : null}
        <Button
          onClick={() => {
            if (_.isEmpty(state.taskKeys)) {
              message.info('请选择要查看的申请');
              return;
            }
            loadRunStep(state.taskKeys![state.taskKeys!.length - 1]);
          }}
        >
          <IconFont type="icon-chakanjindu" />
          查看进度
        </Button>
        {state.range === 'firstdoing' || state.range === 'doing' || state.range === 'manager' ? (
          <Button onClick={batchSubmitHandler} disabled={state.loading}>
            <IconFont type="icon-tijiao" />
            提交
          </Button>
        ) : null}
        {state.range === 'manager' || state.range === 'doing' ? (
          <Button onClick={abortHandler} disabled={state.loading}>
            <IconFont type="icon-zhongzhi" />
            中止
          </Button>
        ) : null}
        {state.range === 'manager' ? (
          <Button onClick={actHandler} disabled={state.loading}>
            <IconFont type="icon-jihuo" />
            激活
          </Button>
        ) : null}
        {state.range === 'firstdoing' && canImport ? (
          <Button onClick={() => dispatch({ showImport: true })}>
            <IconFont type="icon-daoru" />
            导入
          </Button>
        ) : null}
        {state.range === 'firstdoing' && canImport ? (
          <Button onClick={() => downLoadTemplateFile(props.importTemplateName)}>
            <IconFont type="icon-xiazaimoban" />
            下载导入模板
          </Button>
        ) : null}
      </Space>
    );
  }, [
    state.isMg,
    props.showType,
    permTypes,
    props.importTemplateName,
    props.taskDaoName,
    state.taskKeys,
    state.taskRows,
    user,
    getTitle,
    loadFlowDoing,
    loadRunStep,
    state.loading,
    state.range,
  ]);
  const renderDetail = useCallback(() => {
    let row: Record<string, any> | undefined = undefined;
    if (!_.isEmpty(state.taskRows)) {
      row = state.taskRows![state.taskRows!.length - 1];
    }
    if (row === undefined) {
      return <Alert message="" description="请在左面选择申请" type="info" />;
    }
    return (
      <>
        <Descriptions title="" column={2}>
          {state.taskColumns!.map((c) => {
            let val: string = '';
            if (c.dataType === 'date') {
              val = format(row![c.key!], 'yyyy-MM-dd');
            } else if (c.dataType === 'datetime') {
              val = format(row![c.key!], 'yyyy-MM-dd hh:mm:ss');
            } else if (c.dataType === 'number') {
              val = renderNumber('.2f', row![c.key!]);
            } else {
              val = row![c.key!];
            }
            return (
              <Descriptions.Item key={c.key} label={c.title}>
                {val}
              </Descriptions.Item>
            );
          })}
        </Descriptions>
        {props.isUpdate ? (
          <>
            <Descriptions title="原客户经理" />
            {row.Bgqdivi
              ? (row.Bgqdivi as Record<string, any>[]).map((k, i) => {
                  return (
                    <Descriptions key="ykhjl" column={3}>
                      <Descriptions.Item key="emno" label={`员工号${i + 1}`}>
                        {k.EMNO}
                      </Descriptions.Item>
                      <Descriptions.Item key="emnm" label={`员工名称${i + 1}`}>
                        {k.EMNM}
                      </Descriptions.Item>
                      <Descriptions.Item
                        key="davl"
                        label={props.diviType === 'money' ? `金额${i + 1}(元)` : `占比${i + 1}(%)`}
                      >
                        {k.DSVL * (props.diviType === 'money' ? 1 : 100)}
                      </Descriptions.Item>
                    </Descriptions>
                  );
                })
              : null}
            {row.BeiZhu != '' ? <Descriptions title="备注" /> : null}
            {row.BeiZhu != '' ? (
              <Descriptions>
                <Descriptions.Item label="">{row.BeiZhu}</Descriptions.Item>
              </Descriptions>
            ) : null}
          </>
        ) : null}
      </>
    );
  }, [state.taskColumns, state.taskRows, props.isUpdate, props.diviType]);
  const dataTable = useMemo(() => {
    if (_.isEmpty(state.taskDaoName) || _.isEmpty(state.taskColumns) || _.isEmpty(state.range)) {
      return;
    }
    return (
      <Card title="申请列表" bodyStyle={{ padding: 0 }}>
        <DataTable
          daoName={state.taskDaoName!}
          columns={state.taskColumns!}
          keyColName="FRID"
          initSorter={{ FieldName: 'SQDT', Direction: 'ASC' }}
          pageSize={20}
          seeks={[
            {
              WhereItems: [
                {
                  FieldName: '#flowType',
                  Operator: '=',
                  FieldValues: state.range!,
                },
              ],
              RelationSign: 'AND',
            },
          ]}
          actionRef={tableRef}
          title={props.title}
          multiSelect={true}
          onSelectChange={async (keys, rows) => {
            const rIds = keys as number[];
            dispatch({ taskKeys: rIds, taskRows: rows });
          }}
        />
      </Card>
    );
  }, [state.taskDaoName, state.taskColumns, props.title, state.range]);
  const taskList = useMemo(() => {
    if (_.isEmpty(state.taskColumns)) {
      return;
    }
    return (
      <Row>
        <Col key="1" span={14} style={{ paddingRight: 10 }}>
          {dataTable}
        </Col>
        <Col key="2" span={10}>
          <Card title="详细信息" bodyStyle={{ padding: 10 }}>
            {renderDetail()}
          </Card>
        </Col>
      </Row>
    );
  }, [state.taskColumns, renderDetail, dataTable]);
  const searchModal = useMemo(() => {
    if (!state.showSeach) {
      return;
    }
    const searchSubmit = async (vals: Record<string, any>) => {
      const seek: API.WhereCause = { WhereItems: [], RelationSign: 'AND' };
      props.searchControls.forEach((c) => {
        if (vals[c.name] && vals[c.name] !== '') {
          let val = vals[c.name];
          if (
            c.type === 'date' ||
            c.dataType === 'date' ||
            c.type === 'datetime' ||
            c.dataType === 'datetime'
          ) {
            val = format(val, 'yyyy-MM-dd');
          } else {
            val = String(val);
          }
          seek.WhereItems.push({
            FieldName: c.name,
            Operator: '=',
            FieldValues: val,
          });
        }
      });
      if (_.isEmpty(seek.WhereItems)) {
        message.error('请数据查找条件');
      }
      dispatch({ searchSeeks: [seek] });
    };
    const saveDivi = async (values: Record<string, any>) => {
      values.UID = user?.userID;
      values.SQR = user?.name;
      if (props.userIsFirstEmpl) {
        values.EMNO1 = user?.no;
      } else {
        if (_.isEmpty(values.EMNO1)) {
          message.error('必须搜索和选择员工1');
          return;
        }
      }
      if (!values.DSVL1) {
        const desc = props.diviType === 'percent' ? '占比' : '金额';
        message.error(`必须输入${desc}1`);
        return;
      }
      let newDatas: Record<string, any>[] = [];
      if (!props.isClientDivi) {
        if (_.isEmpty(state.searchKeys)) {
          message.error('请选择要认定的账户,可以多选');
          return;
        }
        newDatas = state.searchKeys!.map((k) => {
          return { [props.searchKeyColName]: k, ...values };
        });
      } else {
        if (state.cuid) {
          newDatas = [{ CUID: state.cuid, ...values }];
        }
      }
      dispatch({ loading: true });
      submitDatas(props.taskDaoName, newDatas, [], [])
        .then(function () {
          loadFlowDoing();
          if (!_.isEmpty(tableRef.current)) {
            tableRef.current?.reload();
          }
          dispatch({
            range: 'firstdoing',
            loading: false,
            showSeach: false,
            searchSeeks: initsearchSeeks(),
          });
        })
        .catch(function (ex) {
          dispatch({ loading: false });
          console.error('判断流程管理员出错', ex);
        });
    };
    const title = (
      <div>
        <span>{props.title}</span>
        <span style={{ fontSize: 14, color: 'red', float: 'right', marginRight: 20 }}>
          {props.subhead}
        </span>
      </div>
    );
    return (
      <Modal
        title={title}
        maskClosable={false}
        width={1000}
        visible={state.showSeach}
        onOk={() => formRef.current?.submit()}
        onCancel={() => dispatch({ showSeach: false })}
        bodyStyle={{ paddingTop: 0, paddingBottom: 0 }}
        footer={[
          <Button
            key="import"
            type="primary"
            disabled={state.loading}
            onClick={() => formRef.current?.submit()}
          >
            保存
          </Button>,
          <Button
            key="close"
            type="ghost"
            disabled={state.loading}
            onClick={() => dispatch({ showSeach: false })}
          >
            关闭
          </Button>,
        ]}
      >
        <div style={{ marginTop: 10, marginBottom: 10 }}>
          <DataEdit
            key="searchBar"
            controls={props.searchControls}
            showType="inner"
            layout="inline"
            autoFocusFirstInput={false}
            onSumit={searchSubmit}
            grid={false}
            renderButtons={(p) => {
              return [
                <Space key="extraButtons">
                  <Button type="primary" key="new" onClick={() => p.form?.submit?.()}>
                    查找
                  </Button>
                </Space>,
              ];
            }}
          />
        </div>
        <DataTable
          key="searchTable"
          daoName={props.searchDaoName}
          columns={props.searchColumns}
          keyColName={props.searchKeyColName}
          initSorter={props.searchOrder}
          pageSize={20}
          height={380}
          canClearFilter={false}
          canExport={false}
          multiSelect={!props.isClientDivi}
          canSelectRow={!props.isClientDivi}
          canSelectItems={false}
          seeks={state.searchSeeks}
          title={props.title}
          onSelectChange={async (keys) => {
            dispatch({ searchKeys: keys as number[] });
          }}
          onDataChange={async (rows) => {
            let cuid = undefined;
            if (rows && rows[0] && rows[0].CUID) {
              cuid = rows[0].CUID;
            }
            dispatch({ cuid });
          }}
        />
        <div style={{ marginTop: 10 }}>
          <DataEdit
            formRef={formRef}
            key="emplDivi"
            controls={state.diviControls!}
            initVals={props.userIsFirstEmpl ? { EMNO1: user!.name! } : undefined}
            showType="inner"
            layout="horizontal"
            autoFocusFirstInput={false}
            onSumit={saveDivi}
            renderButtons={false}
          />
        </div>
      </Modal>
    );
  }, [
    state.showSeach,
    state.loading,
    state.searchSeeks,
    state.diviControls,
    state.searchKeys,
    state.cuid,
    props.title,
    props.subhead,
    props.searchControls,
    props.searchDaoName,
    props.searchColumns,
    props.searchKeyColName,
    props.searchOrder,
    props.isClientDivi,
    props.userIsFirstEmpl,
    props.taskDaoName,
    props.diviType,
    user,
    loadFlowDoing,
    initsearchSeeks,
  ]);
  const importModal = useMemo(() => {
    if (!state.showImport) {
      return;
    }
    return (
      <DataImport
        importName={props.importName!}
        importMode="InsertOnly"
        daoName={props.taskDaoName}
        controls={state.importControls!}
        title={props.title!}
        visible={state.showImport}
        paramVals={{ UID: '' + user?.userID, SQR: user!.name! }}
        onVisibleChange={(show) => {
          dispatch({ showImport: show });
          if (!show) {
            loadFlowDoing();
            if (!_.isEmpty(tableRef.current)) {
              tableRef.current?.reload();
            }
          }
        }}
      />
    );
  }, [
    state.showImport,
    props.importName,
    props.taskDaoName,
    state.importControls,
    props.title,
    user,
    loadFlowDoing,
  ]);
  return (
    <PageHeader>
      {toolBar}
      {taskList}
      {searchModal}
      {importModal}
      {state.runStep}
    </PageHeader>
  );
};

WorkflowDivi.defaultProps = {
  userIsFirstEmpl: true,
  diviType: 'percent',
  isClientDivi: false,
  canSetDiviDate: true,
};

export default WorkflowDivi;
